package com.example.book.controller;

import com.example.book.constant.Constants;
import com.example.book.model.UserInfo;
import com.example.book.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/user")
@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public boolean login(String userName, String password, HttpSession session) {
        log.info("登入用户userName: {}, password: {}",userName,password);
        // 判断账号密码是否有效
        if( !StringUtils.hasLength(userName) ||
                !StringUtils.hasLength(password)) {
            return false;
        }
        // 根据用户名获取用户信息
        UserInfo userInfo = userService.getUserByName(userName);
        // 效验是否为有效用户
        if(userInfo == null || userInfo.getId() < 0) {
            return false;
        }
        // 判断密码是否正确
        if(password.equals(userInfo.getPassword())) {
            userInfo.setPassword("");
            session.setAttribute(Constants.SESSION_USER_KEY,userInfo);
            return true;
        }
        return false;
    }
}
